package com.big.spike.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.big.common.utils.DateUtils;
import com.big.common.utils.RedisScript;
import com.big.merchandise.MerchandiseFeignClient;
import com.big.model.model.merchandise.MerchandiseDetail;
import com.big.model.model.merchandise.MerchandiseInfo;
import com.big.model.model.merchandise.MerchandiseSpike;
import com.big.model.model.patient.PatientInfo;
import com.big.patient.PatientFeignClient;
import com.big.spike.mapper.MerchandiseSpikeMapper;
import com.big.spike.service.MerchandiseSpikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
@Slf4j
public class MerchandiseSpikeServiceImpl extends ServiceImpl<MerchandiseSpikeMapper, MerchandiseSpike> implements MerchandiseSpikeService {


    @Autowired
    MerchandiseFeignClient merchandiseFeignClient;


    @Autowired
    PatientFeignClient patientFeignClient;

    @Autowired
    RedisTemplate redisTemplate;



    @Autowired
    RedisScript redisScript= RedisScript.getInstance();


    /**
     * 秒杀列表
     * @param page
     * @return
     */
    @Override
    public IPage<MerchandiseSpike> MerchandiseSpike(Page<MerchandiseSpike> page) {

        IPage<MerchandiseSpike> merchandiseSpikeIPage = baseMapper.selectPage(page, null);
        merchandiseSpikeIPage.getRecords().forEach(item -> {
           this.info(item);
        });
        return merchandiseSpikeIPage;
    }


    //添加商品秒杀缓存
    @Override
    public void spikesRedis(Long spikeId) throws ParseException {
        QueryWrapper<MerchandiseSpike> queryWrapper =new QueryWrapper<>();
        queryWrapper.eq("id",spikeId);
        MerchandiseSpike merchandiseSpike = baseMapper.selectOne(queryWrapper);

        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        String startTime=sdf.format(merchandiseSpike.getStartTime());
        String endTime=sdf.format(merchandiseSpike.getEndTime());

        Long startLong = DateUtils.msUtils(DateUtils.getDate(), startTime);
        Long nedLong = DateUtils.msUtils(startTime,endTime );
        log.info("起始redis时间{}",startLong);
        log.info("结束redis{}",nedLong);
        //当前时间到开始时间-倒计时
        redisTemplate.opsForValue().set("spike_start_"+merchandiseSpike.getDid(), merchandiseSpike, startLong, TimeUnit.SECONDS);
        //开始时间到结束时间-倒计时
        redisTemplate.opsForValue().set("spike_end_"+merchandiseSpike.getDid(), merchandiseSpike, nedLong, TimeUnit.SECONDS);
    }


    /**
     * 修改秒杀状态   准备开始-已开始-已结束
     * @param spikeId
     * @return
     */
    @Override
    public Boolean upSpike(Long spikeId,Integer typeCode) {
        UpdateWrapper<MerchandiseSpike>updateWrapper=new UpdateWrapper<>();
        updateWrapper.eq("id",spikeId).set("status",typeCode);
        return baseMapper.update(null,updateWrapper)==1?true:false;
    }


    /**
     * 提醒我
     * @param uId
     * @param mId
     * @return
     */
    @Override
    public boolean MerchRemindMe(String uId, String mId) throws ParseException {
        PatientInfo userById = patientFeignClient.findUserById(uId);
        MerchandiseSpike merchandiseSpike = this.spikeInfo(mId);
        SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        //获取当前时间
        String startTime=sdf.format(merchandiseSpike.getStartTime());
        Long startLong = DateUtils.msUtils(DateUtils.getDate(), startTime);
        //当前时间到开始时间-倒计时
//        redisTemplate.opsForValue().set(userById.getUserId(), merchandiseSpike, startLong-600L, TimeUnit.SECONDS);
        if(this.remindMe(userById.getPhone())){
            //已有
            return  false;
        }
        redisTemplate.opsForValue().set(userById.getPhone(), merchandiseSpike, 10, TimeUnit.SECONDS);
        return true;
    }

    @Override
    public MerchandiseSpike spikeInfo(String mId) {
        QueryWrapper<MerchandiseSpike>queryWrap=new QueryWrapper<>();
        queryWrap.eq("id",mId);
        MerchandiseSpike merchandiseSpike = baseMapper.selectOne(queryWrap);
        return merchandiseSpike;
    }

    @Override
    public boolean remindMe(String phone) {
        List<String>keys=Arrays.asList(phone);
        Boolean execute= (Boolean) redisTemplate.execute(redisScript.remindMe, keys);
        log.info("值：{}",execute);
        return  execute;
    }


    public MerchandiseSpike info(MerchandiseSpike merchandiseSpike){
        MerchandiseInfo infoMerchandise = merchandiseFeignClient.findInfoMerchandise(String.valueOf(merchandiseSpike.getDid()));
        MerchandiseDetail merchandiseDetail = merchandiseFeignClient.FindMerchanInfo(String.valueOf(merchandiseSpike.getDid()));
        merchandiseSpike.getParam().put("name",infoMerchandise.getName());
        merchandiseSpike.getParam().put("dimage",merchandiseDetail.getDImage());
        merchandiseSpike.getParam().put("dintro",merchandiseDetail.getDIntro());
        merchandiseSpike.getParam().put("did",merchandiseDetail.getDId());
        merchandiseSpike.getParam().put("selling_price",infoMerchandise.getSellingPrice());
        merchandiseSpike.getParam().put("original_price",infoMerchandise.getOriginalPrice());
        switch (merchandiseSpike.getStatus()){
            case 0:
                merchandiseSpike.getParam().put("statusName","准备开始");
                break;
            case 1:
                merchandiseSpike.getParam().put("statusName","已开始");
                break;
            case 2:
                merchandiseSpike.getParam().put("statusName","已结束");
                break;
        }

        return  merchandiseSpike;
    }

}
